package com.example.fengyungo_user.activity.login;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.example.fengyungo_user.R;
import com.example.fengyungo_user.activity.BaseActivity;
import com.example.fengyungo_user.constant.ResultConstant;
import com.example.fengyungo_user.constant.UserConstant;
import com.example.fengyungo_user.utils.CountDownTimerUtils;
import com.example.fengyungo_user.utils.OkHttpUtils;
import com.example.fengyungo_user.utils.ThreadPoolUtil;
import com.google.android.material.textfield.TextInputLayout;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

/**
 * @author XLR
 */
public class RegisterActivity extends BaseActivity {

    private static final String TAG = "RegisterActivity";

    /**
     * 用户名处TextInputLayout
     */
    TextInputLayout inputUsername;
    /**
     * 密码处TextInputLayout
     */
    TextInputLayout inputPassword;
    /**
     * 确认密码处TextInputLayout
     */
    TextInputLayout inputPasswordAgain;
    /**
     * 邮箱处TextInputLayout
     */
    TextInputLayout inputMail;
    /**
     * 验证码处TextInputLayout
     */
    TextInputLayout inputCode;
    /**
     * 用户名输入框
     */
    EditText registerUsernameEditText;
    /**
     * 密码输入框
     */
    EditText registerPasswordEditText;
    /**
     * 确认密码输入框
     */
    EditText registerPasswordAgainEditText;
    /**
     * 邮箱输入框
     */
    EditText registerMailEditText;
    /**
     * 验证码输入框
     */
    EditText registerCodeEditText;
    /**
     * 注册按钮
     */
    Button register;
    /**
     * 发送验证码按钮
     */
    Button sendCode;
    /**
     * 返回按钮
     */
    ImageView back;
    /**
     * 用户名
     */
    String registerUsername;
    /**
     * 密码
     */
    String registerPassword;
    /**
     * 确认密码
     */
    String registerPasswordAgain;
    /**
     * 邮箱
     */
    String registerMail;
    /**
     * 验证码
     */
    String registerCode;
    /**
     * 进度条
     */
    ProgressBar progressBar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);

        // 进度条
        progressBar = findViewById(R.id.progress_bar);
        // 按钮
        register = findViewById(R.id.register1);
        back = findViewById(R.id.back);
        sendCode = findViewById(R.id.send_code);

        registerUsernameEditText = findViewById(R.id.username);
        registerPasswordEditText = findViewById(R.id.password);
        registerPasswordAgainEditText = findViewById(R.id.password_again);
        registerCodeEditText = findViewById(R.id.code);
        registerMailEditText = findViewById(R.id.mail);

        inputUsername = findViewById(R.id.input_username);
        inputPassword = findViewById(R.id.input_password);
        inputPasswordAgain = findViewById(R.id.input_password_again);
        inputCode = findViewById(R.id.input_code);
        inputMail = findViewById(R.id.input_mail);

        register.setOnClickListener(view -> register());

        back.setOnClickListener(view -> finish());

        sendCode.setOnClickListener(view -> sendCodeMail());

    }

    /**
     * 判断邮箱是否注册
     *
     * @return JSONObject
     * @throws JSONException JSONException
     * @throws IOException   IOException
     */
    private JSONObject judgeMail() throws JSONException, IOException {
        String url = UserConstant.URL_USER_USER + "/judgeMail/" + registerMail;
        String responseData = OkHttpUtils.get(url);

        JSONObject jsonObjectForJudge = new JSONObject(responseData);
        return jsonObjectForJudge;
    }

    /**
     * 发送验证码到邮箱
     */
    private void sendCodeMail() {
        boolean cancel = false;
        View focusView = null;

        registerMail = registerMailEditText.getText().toString();
        inputMail.setError(null);
        if (registerMail.isEmpty()) {
            inputMail.setError(getString(R.string.input_mail));
            focusView = registerMailEditText;
            cancel = true;
        }
        // 未输入邮箱
        if (cancel) {
            // 获得焦点
            focusView.requestFocus();
        } else {
            progressBar.setVisibility(View.VISIBLE);
            // 发送验证码
            Runnable runnable = new Runnable() {
                @Override
                public void run() {
                    try {
                        // 判断邮箱是否已被注册
                        JSONObject jsonObjectForJudge = judgeMail();
                        int resForJudge = jsonObjectForJudge.getInt(ResultConstant.CODE);
                        String msg = jsonObjectForJudge.getString(ResultConstant.MSG);
                        if (resForJudge == 0) {
                            runOnUiThread(() -> {
                                progressBar.setVisibility(View.GONE);
                                Toast.makeText(RegisterActivity.this, msg, Toast.LENGTH_SHORT).show();
                            });
                        } else {
                            // 邮箱未被注册，发送验证码
                            // 发送GET请求到后端，并接收响应数据
                            String url = UserConstant.URL_USER_USER + "/send/" + registerMail;
                            String responseData = OkHttpUtils.get(url);

                            Log.d(TAG, "run: responseData:" + responseData);
                            JSONObject jsonObject = new JSONObject(responseData);
                            Boolean send = jsonObject.getBoolean(ResultConstant.DATA);
                            Log.d(TAG, "run: send=" + send);
                            if (send) {
                                runOnUiThread(() -> {
                                    progressBar.setVisibility(View.GONE);
                                    Toast.makeText(RegisterActivity.this, getString(R.string.code_send_success), Toast.LENGTH_LONG).show();
                                    CountDownTimerUtils countDownTimerUtils = new CountDownTimerUtils(sendCode, 60000, 1000);
                                    countDownTimerUtils.start();
                                });
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        runOnUiThread(() -> {
                            progressBar.setVisibility(View.GONE);
                            Toast.makeText(RegisterActivity.this, getString(R.string.connection_error), Toast.LENGTH_SHORT).show();
                        });
                    }
                }
            };
            ThreadPoolUtil.execute(runnable);
        }
    }

    /**
     * 获取输入框输入的用户名、密码、确认密码、邮箱、验证码
     */
    private void getFromEditText() {
        registerUsername = registerUsernameEditText.getText().toString();
        registerPassword = registerPasswordEditText.getText().toString();
        registerPasswordAgain = registerPasswordAgainEditText.getText().toString();
        registerMail = registerMailEditText.getText().toString();
        registerCode = registerCodeEditText.getText().toString();
    }

    /**
     * 注册
     */
    private void register() {
        boolean cancel = false;
        View focusView = null;

        // 获取输入框输入的用户名、密码、确认密码、邮箱、验证码
        getFromEditText();

        inputUsername.setError(null);
        inputPassword.setError(null);
        inputPasswordAgain.setError(null);
        inputMail.setError(null);
        inputCode.setError(null);

        if (registerMail.isEmpty()) {
            inputMail.setError(getString(R.string.input_mail));
            focusView = registerMailEditText;
            cancel = true;
        } else if (registerUsername.isEmpty()) {
            inputUsername.setError(getString(R.string.input_username));
            focusView = registerUsernameEditText;
            cancel = true;
        } else if (registerPassword.isEmpty()) {
            inputPassword.setError(getString(R.string.input_password));
            focusView = registerPasswordEditText;
            cancel = true;
        } else if (registerPasswordAgain.isEmpty()) {
            inputPasswordAgain.setError(getString(R.string.ensure_password));
            focusView = registerPasswordAgainEditText;
            cancel = true;
        } else if (registerCode.isEmpty()) {
            inputCode.setError(getString(R.string.input_code));
            focusView = registerCodeEditText;
            cancel = true;
        }

        if (cancel) {
            // 出现错误的账号或者密码的View获得焦点
            focusView.requestFocus();
        } else {
            // 密码与确认密码相同
            if (registerPassword.equals(registerPasswordAgain)) {
                // 验证账号是否已存在、验证码的验证、新增用户
                progressBar.setVisibility(View.VISIBLE);
                Runnable runnable = () -> {
                    try {
                        JSONObject userJson = new JSONObject();
                        userJson.put(UserConstant.USERNAME, registerUsername);
                        userJson.put(UserConstant.PASSWORD, registerPassword);
                        userJson.put(UserConstant.MAIL, registerMail);
                        // Driver 实体类的 JSON 格式数据
                        String json = userJson.toString();

                        // 验证账号是否已存在
                        String url = UserConstant.URL_USER_USER + "/judgeUsername/" + registerUsername;
                        String dataForJudge = OkHttpUtils.get(url);

                        JSONObject jsonObjectForJudge = new JSONObject(dataForJudge);
                        int resForJudge = jsonObjectForJudge.getInt(ResultConstant.CODE);
                        String msg = jsonObjectForJudge.getString(ResultConstant.MSG);
                        if (resForJudge == 0) {
                            runOnUiThread(() -> {
                                progressBar.setVisibility(View.GONE);
                                Toast.makeText(RegisterActivity.this, msg, Toast.LENGTH_SHORT).show();
                            });
                        } else {
                            // 发送GET请求到后端，并接收响应数据
                            String urlForVer = UserConstant.URL_USER_USER + "/" + registerMail + "/" + registerCode;
                            String jsonDataForVerification = OkHttpUtils.get(urlForVer);

                            Log.d(TAG, "run: data:" + jsonDataForVerification);
                            JSONObject jsonObjectForVerification = new JSONObject(jsonDataForVerification);
                            Boolean verification = jsonObjectForVerification.getBoolean(ResultConstant.DATA);
                            Log.d(TAG, "run: verification=" + verification);
                            // 验证通过
                            if (verification) {
                                Log.d(TAG, "run: json" + json);

                                String urlForAdd = UserConstant.URL_USER_USER + "/register";
                                String jsonDataForAdd = OkHttpUtils.post(urlForAdd, json);

                                Log.d(TAG, "run: data:" + jsonDataForAdd);
                                JSONObject jsonObject2 = new JSONObject(jsonDataForAdd);
                                Boolean register = jsonObject2.getBoolean(ResultConstant.DATA);
                                Log.d(TAG, "run: register:" + register);
                                if (register) {
                                    runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            progressBar.setVisibility(View.GONE);
                                            Toast.makeText(RegisterActivity.this, getString(R.string.register_success), Toast.LENGTH_SHORT).show();
                                            finish();
                                        }
                                    });
                                }
                            } else {
                                runOnUiThread(() -> {
                                    progressBar.setVisibility(View.GONE);
                                    Toast.makeText(RegisterActivity.this, getString(R.string.code_error), Toast.LENGTH_SHORT).show();
                                });
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        runOnUiThread(() -> {
                            progressBar.setVisibility(View.GONE);
                            Toast.makeText(RegisterActivity.this, getString(R.string.connection_error), Toast.LENGTH_SHORT).show();
                        });
                    }
                };
                ThreadPoolUtil.execute(runnable);
            }
            // 密码与确认密码不相同
            else {
                Toast.makeText(RegisterActivity.this, getString(R.string.password_different), Toast.LENGTH_SHORT).show();
            }
        }
    }
}